package org.samith.web.servlet;

import java.io.IOException;

import javax.ejb.EJB;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.samith.dao.UserDao;
import org.samith.entity.User;

@SuppressWarnings("serial")
public class AccountVerificationServlet extends HttpServlet {

	@EJB
	UserDao userDao;
	
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		ServletContext context = getServletConfig().getServletContext();
		HttpSession session = request.getSession();
		Object token = session.getAttribute("verificationCode");
		if (token != null) {
			context.getRequestDispatcher("/SignUp/signupSuccess.jsp").forward(
					request, response);
		} else {
			context.getRequestDispatcher("/SignUp/index.jsp").forward(request,
					response);
		}

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		ServletContext context = getServletConfig().getServletContext();
		HttpSession session = request.getSession();
		Object token = session.getAttribute("verificationCode");
		if (token != null && request.getParameter("passcode") != null) {
			String tokn = (String)token;
			if(tokn.equals(request.getParameter("passcode"))){
				User user = userDao.findByAuthToken(tokn);
				if(user != null)
					user.setIsActive(new Byte("1"));
				userDao.update(user);
				context.getRequestDispatcher("/").forward(
						request, response);
			}else{
				context.getRequestDispatcher("/SignUp/signupSuccess.jsp").forward(
						request, response);
			}
			
		} else {
			context.getRequestDispatcher("/SignUp/index.jsp").forward(request,
					response);
		}
	}
}
